package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hpplay.sdk.source.api.IConnectListener;
import com.hpplay.sdk.source.browse.api.IBrowseListener;
import com.hpplay.sdk.source.browse.api.LelinkServiceInfo;
import com.stark.cast.screen.CastScreenManager;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.List;

import flc.ast.AppConfig;
import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SearchAdapter;
import flc.ast.adapter.SelVideoAdapter;
import flc.ast.databinding.ActivitySelVideoBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.view.container.StkRecycleView;

public class SelVideoActivity extends BaseAc<ActivitySelVideoBinding> {

    private SelVideoAdapter selVideoAdapter;
    private List<SelectMediaEntity> listShow = new ArrayList<>();
    private List<SelectMediaEntity> listSel = new ArrayList<>();//选择的集合
    private CastScreenManager mCastScreenManager;
    private boolean isSearch = false;
    private Dialog mySearchDialog;
    private StkRecycleView dialogSearchList;
    private int oldPosition;
    private SearchAdapter searchAdapter;

    @Override
    protected int onCreate() {
        return R.layout.activity_sel_video;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSelVideoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivProVideoStart.setOnClickListener(this);
        mDataBinding.rvSelVideoList.setLayoutManager(new GridLayoutManager(mContext, 3));
        selVideoAdapter = new SelVideoAdapter();
        mDataBinding.rvSelVideoList.setAdapter(selVideoAdapter);
        selVideoAdapter.setOnItemClickListener(this);
        mCastScreenManager = CastScreenManager.getInstance();
        //投屏弹框
        searchDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivProVideoStart:
                if (listSel.size()==0){
                    ToastUtils.showShort(getString(R.string.please_sel_video));
                    return;
                }
                if (Content.IsConnect) {
                    ProVideoActivity.listPlay=listSel;
                    startActivity(ProVideoActivity.class);
                } else {
                    //注册投屏
                    registerScreen();
                    mySearchDialog.show();
                }
                break;
            case R.id.tvDialogSearchAnew://重新搜索
                if (isSearch) return;
                isSearch = true;
                mCastScreenManager.startBrowse();
                break;
            case R.id.tvDialogSearchCancel:
                mySearchDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (selVideoAdapter.getItem(position).isChecked()) {
            selVideoAdapter.getItem(position).setChecked(false);
            listSel.remove(selVideoAdapter.getItem(position));
        } else {
            selVideoAdapter.getItem(position).setChecked(true);
            listSel.add(selVideoAdapter.getItem(position));
        }
        mDataBinding.tvSelectedNum.setText(getString(R.string.selected_material, listSel.size()));
        selVideoAdapter.notifyItemChanged(position);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivSearchItemSel:
                if (searchAdapter.getItem(position).isConnect()) {
                    Content.IsConnect = false;
                    searchAdapter.getItem(position).setConnect(false);
                    searchAdapter.notifyDataSetChanged();
                    mCastScreenManager.disConnect();
                    Content.ConnectName = "";
                } else {
                    Content.IsConnect = true;
                    searchAdapter.getItem(oldPosition).setConnect(false);
                    oldPosition = position;
                    searchAdapter.getItem(position).setConnect(true);
                    searchAdapter.notifyDataSetChanged();
                    mCastScreenManager.connect(searchAdapter.getItem(position));
                    Content.ConnectName = searchAdapter.getItem(position).getName();
                }
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
        mDataBinding.tvSelectedNum.setText(getString(R.string.selected_material, listSel.size()));
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO).reqPermissionDesc(getString(R.string.get_storage_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                getData();
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                mDataBinding.rvSelVideoList.setVisibility(View.GONE);
                mDataBinding.tvSelVideoNoData.setVisibility(View.VISIBLE);
            }
        }).request();
    }

    //获取视频和图片数据
    private void getData() {
        listShow.clear();
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    listShow.addAll(selectMediaEntities);
                    selVideoAdapter.setList(listShow);
                    mDataBinding.rvSelVideoList.setVisibility(View.VISIBLE);
                    mDataBinding.tvSelVideoNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvSelVideoList.setVisibility(View.GONE);
                    mDataBinding.tvSelVideoNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    //注册投屏
    private void registerScreen() {
        CastScreenManager.init(AppConfig.TEST_APP_ID, AppConfig.TEST_APP_SECRET);
        mCastScreenManager = CastScreenManager.getInstance();
        mCastScreenManager.setListener(new CastScreenManager.AListener() {
            @Override
            public void onInit(boolean success) {
                dismissDialog();
                //ToastUtils.showLong(success ? getString(R.string.init_suc) : getString(R.string.init_def));
                if (success) {
                    Content.IsInit = true;
                    //isSearch = true;
                    //showDialog(getString(R.string.search_ing));
                    mCastScreenManager.startBrowse();
                } else {
                    Content.IsInit = false;
                }
            }

            @Override
            public void onBrowse(int code, List<LelinkServiceInfo> list) {
                dismissDialog();
                isSearch = false;
                if (code == IBrowseListener.BROWSE_SUCCESS) {
                    if (searchAdapter != null) {
                        dialogSearchList.setVisibility(View.VISIBLE);
                        searchAdapter.setList(list);
                        //回显连接状态
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getName().equals(Content.ConnectName)) {
                                list.get(i).setConnect(true);
                            }
                        }
                        searchAdapter.notifyDataSetChanged();
                    } else {
                        dialogSearchList.setVisibility(View.GONE);
                    }
                } else if (code == IBrowseListener.BROWSE_TIMEOUT) {
                    ToastUtils.showLong(R.string.search_over);
                } else if (code == IBrowseListener.BROWSE_ERROR_AUTH || code == IBrowseListener.BROWSE_ERROR_AUTH_TIME) {
                    ToastUtils.showLong(R.string.auth_def);
                }
            }

            @Override
            public void onConnect(LelinkServiceInfo lelinkServiceInfo, int connectType) {
                String strProtocol = getString(R.string.no_agreement);
                switch (connectType) {
                    case IConnectListener.TYPE_LELINK:
                        strProtocol = getString(R.string.lelian_agreement);
                        break;
                    case IConnectListener.TYPE_DLNA:
                        strProtocol = getString(R.string.dlna_agreement);
                        break;
                    case IConnectListener.TYPE_IM:
                        strProtocol = getString(R.string.im_agreement);
                        break;
                }
                if (lelinkServiceInfo.getName() != null && !TextUtils.isEmpty(lelinkServiceInfo.getName())) {
                    Content.IsConnect = true;
                    Content.ConnectName = lelinkServiceInfo.getName();
                } else {
                    Content.IsConnect = false;
                    Content.ConnectName = "";
                }
                ToastUtils.showLong(getString(R.string.conn_device) + lelinkServiceInfo.getName() + getString(R.string.agreement_to) + strProtocol);
            }

            @Override
            public void onDisconnect(LelinkServiceInfo lelinkServiceInfo, int what, int extra) {
                Content.IsConnect = false;
                String text = getString(R.string.break_device) + lelinkServiceInfo.getName();
                if (what == IConnectListener.WHAT_HARASS_WAITING) {// 防骚扰，等待用户确认
                    // 乐播投屏防骚扰等待消息
                    text = lelinkServiceInfo.getName() + getString(R.string.wait_right);
                } else if (what == IConnectListener.WHAT_DISCONNECT) {
                    switch (extra) {
                        case IConnectListener.EXTRA_HARASS_REJECT:// 防骚扰，用户拒绝投屏
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_refuse);
                            break;
                        case IConnectListener.EXTRA_HARASS_TIMEOUT:// 防骚扰，用户响应超时
                            text = lelinkServiceInfo.getName() + getString(R.string.saorao_request_over);
                            break;
                        case IConnectListener.EXTRA_HARASS_BLACKLIST:// 防骚扰，该用户被加入黑名单
                            text = lelinkServiceInfo.getName() + getString(R.string.black_list);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_break);
                            break;
                    }
                } else if (what == IConnectListener.WHAT_CONNECT_FAILED) {
                    switch (extra) {
                        case IConnectListener.EXTRA_CONNECT_DEVICE_OFFLINE:
                            text = lelinkServiceInfo.getName() + getString(R.string.no_online);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_def);
                            break;
                    }
                }
                ToastUtils.showLong(text);
            }
        });
        if (!Content.IsInit) {
            //showDialog(getString(R.string.init_ing));
            mCastScreenManager.init();
        }
    }

    //投屏弹框
    private void searchDialog() {
        mySearchDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_search, null);
        mySearchDialog.setContentView(inflate);
        mySearchDialog.setCancelable(true);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySearchDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogSearch = inflate.findViewById(R.id.tvDialogSearchAnew);
        TextView cancel = inflate.findViewById(R.id.tvDialogSearchCancel);
        dialogSearch.setOnClickListener(this);
        cancel.setOnClickListener(this);
        dialogSearchList = inflate.findViewById(R.id.rvDialogSearchList);
        dialogSearchList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        searchAdapter = new SearchAdapter();
        dialogSearchList.setAdapter(searchAdapter);
        searchAdapter.addChildClickViewIds(R.id.ivSearchItemSel);
        searchAdapter.setOnItemChildClickListener(this);
    }

}